package com.springboot2.shiro.data.service;

import com.springboot2.shiro.data.enity.Resource;
import com.springboot2.shiro.data.enity.Role;
import com.springboot2.shiro.data.enity.User;
import com.springboot2.shiro.data.repository.ResourceRepository;
import com.springboot2.shiro.data.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * UserServiceImpl
 *
 * @author Archx[archx@foxmail.com]
 * at 2018/7/13 21:30
 */
@Service
public class UserServiceImpl implements UserService {

    private UserRepository repository;

    private ResourceRepository resourceRepository;

    @Autowired
    public void setRepository(UserRepository repository) {
        this.repository = repository;
    }

    @Autowired
    public void setResourceRepository(ResourceRepository resourceRepository) {
        this.resourceRepository = resourceRepository;
    }

    @Override
    public UserRepository getRepository() {
        return repository;
    }

    @Override
    public Set<String> getPermissionsByLogin(String login) {
        User user = repository.findByUsernameEquals(login);

        if (user == null || user.getState() != User.State.Enabled) {
            return Collections.emptySet();
        }

        Role role = user.getRole();
        if (role == null || StringUtils.isEmpty(role.getResourceIds())) {
            return Collections.emptySet();
        }

        List<Integer> resourceIds = Arrays.stream(role.getResourceIds().split(",")).map(Integer::parseInt)
                                          .collect(Collectors.toList());
        return resourceRepository.findAllById(resourceIds).stream().map(Resource::getPermission)
                                 .collect(Collectors.toSet());

    }

    @Cacheable(cacheNames = "user", key = "#login")
    @Override
    public User findByLogin(String login) {
        return repository.findByUsernameEquals(login);
    }
}
